const mongoose = require('mongoose')
const initUsers = require('./initUsers.json')
const initBooks = require('./initBookTypes.json')
const initBookTypes = require('./initBookTypes.json')

const Schema = mongoose.Schema

const userSchema = new Schema({
    user_tel: { type: String },
    password: { type: String },
    user_name: { type: String }
})

const bookSchema = new Schema({
    book_id: { type: Number },
    book_type: { type: Number },
    book_typeName: { type: String },
    book_name: { type: String },
    book_num: { type: Number },
    book_price: { type: Number },
    book_desc: { type: String },
    book_pic: { type: String }
})

const booktypeSchema = new Schema({
    book_type_id: Number,
    book_type_name: String
})


// Mongoose 自带的  Promise 不提供 catch
mongoose.Promise = global.Promise;
// mongoose.Promise = require('bluebird')

const db = {
    User: mongoose.model('User', userSchema),
    Book: mongoose.model('Book', bookSchema),
    BookType: mongoose.model('BookType', booktypeSchema)
}

mongoose.connect('mongodb://127.0.0.1:27017/zlyproject')

var dbConnect = mongoose.connection;



dbConnect.on('error', (error) => {
    console.log('数据库链接失败' + error)
    return
})

dbConnect.once('open', () => {
    console.log('数据库连接成功')

    initData();
})

const initData = function () {
    // 初始化用户model
    db.User.find({}, function (error, doc) {
        if (error) {
            console.log('初始化User出错' + error)
        } else {
            if (!doc.length) {
                console.log('User第一次打开')
                db.User.create(initUsers, function (err, docs) {
                    console.log('初始化User成功', docs)
                })
            } else {
                console.log('不是第一次打开User')
            }
        }
    })

    // 初始化书籍book

    // db.Book.find({}, function (error, doc) {
    //     if (error) {
    //         console.log('初始化Book出错' + error)
    //     } else {
    //         if (!doc.length) {
    //             console.log('Book第一次打开')
    //             db.Book.create(initBooks, function (err, docs) {
    //                 console.log('初始化Book成功', docs)
    //             })
    //         } else {
    //             console.log('不是第一次打开Book')
    //         }
    //     }
    // })
    
    // // 初始化书籍种类
    // db.BookType.find({}, function (error, doc) {
    //     if (error) {
    //         console.log('初始化BookType出错' + error)
    //     } else {
    //         if (!doc.length) {
    //             console.log('BookType第一次打开')
    //             db.BookType.create(initBookTypes, function (err, docs) {
    //                 console.log('初始化BookType成功', docs)
    //             })
    //         } else {
    //             console.log('不是第一次打开BookType')
    //         }
    //     }
    // })

    
}

module.exports=db;




